package com.fit.utils.ee;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * spring SpringUtil 工具类
 * 此工具类只适用于web项目
 * @author hcl
 *
 	 *注意：
 	 * 如果有用到HttpServletRequest对象,需要这web.xml中注册以下监听器
	 *
	<!-- springMvc  request监听器 -->
	<listener>
		<listener-class>
			org.springframework.web.context.request.RequestContextListener
		</listener-class>
	</listener>
 *
 */
public class SpringUtil {
	
	/**
	 * servletContext对象
	 */
	private static ServletContext servletContext = null;
	
	/**
	 * spring对象
	 */
	private static WebApplicationContext spring = null;
	
	
	
	/**
	 * 获取spirng对象
	 * @return
	 */
	public static WebApplicationContext getSpring(){
		if(spring == null){
			synchronized (WebApplicationContext.class) {
				if(spring == null){
					spring = ContextLoader.getCurrentWebApplicationContext();
				}
			}
		}
		return spring;
	}
	
	
	/**
	 * 获取serviceContext对象
	 * @param servletContext
	 */
	public static ServletContext getServletContext(){
		if(servletContext == null){
			synchronized (ServletContext.class) {
				if(servletContext == null){
					servletContext = SpringUtil.getSpring().getServletContext();
				}
			}
		}
		return servletContext;
	}
	
	
	/**
	 * 获取HttpServletRequest对象
	 * @return
	 */
	public static HttpServletRequest getRequest(){
		return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
	}
	
	/**
	 * 获取session对象
	 * @return
	 */
	public static HttpSession getSession(){
		return SpringUtil.getRequest().getSession();
	}
	

	/**
	 * 通过id获取spring中的bean对象
	 * @param beanId
	 * @return
	 */
	public static Object getBean(String beanId){
		return SpringUtil.getSpring().getBean(beanId);
	}
	
	/**
	 * 通过class和获取spring中的bean对象
	 * @param clazz
	 * @return
	 */
	public static <T>T getBean(Class<T> clazz){
		return SpringUtil.getSpring().getBean(clazz);
	}
	
	/**
	 * 通过class和id获取spring中的bean对象
	 * @param beanId
	 * @param clazz
	 * @return
	 */
	public static <T> T getBean(String beanId,Class<T> clazz){
		return SpringUtil.getSpring().getBean(beanId, clazz);
	}
	
	
	/**
	 * 根据bean的class来查找所有的对象(包括子类)
	 * @param clazz
	 * @return 返回key为beanId,value 为bean对象
	 */
	public static <T> Map<String,T> getBeans(Class<T> clazz){
		return SpringUtil.getSpring().getBeansOfType(clazz);
	}
}
